var gulp = require('gulp'),
    fileinclude = require('gulp-file-include'), //合并html
    clean = require('gulp-clean'),   //清除文件
    concat = require('gulp-concat'), //合并文件
    cssmin = require('gulp-cssmin'), //压缩css
    rename = require('gulp-rename'), 
    connect = require('gulp-connect'), //web服务器
    open = require('gulp-open'),       //自动打开浏览器
    os = require('os'),
    webpack = require('webpack'),   
    webpackconfig = require('./webpack.config.js'),
    gulpwebpack = require('gulp-webpack');

var host = {
    path: 'dist/',
    port: 8888,
    index: 'index.html'
};
var browser = os.platform() === 'linux' ? 'google-chrome' : (
    os.platform() === 'darwin' ? 'google chrome' : (
    os.platform() === 'win32' ? 'chrome' : 'firefox'));

//合并html
gulp.task('fileinclude', function(done){
    gulp.src('src/view/*html')
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(gulp.dest('dist/view'))
        .on('end', done);
});

//css 压缩合并
gulp.task('cssmin', function (done) {
    gulp.src('src/css/*.css')  //读取
        .pipe(concat('style.min.css')) //合并css
		.pipe(cssmin())  //压缩 cssmin()
        .pipe(gulp.dest('dist/css')) //输出到dist/css目录下
        .on('end', done);
});
//清除任务
gulp.task('clean', function(done){
    gulp.src(['dist'])
    .pipe(clean())
    .on('end', done);
});

//拷贝图片
gulp.task('copy:images', function(done){
    gulp.src('src/images/*')
        .pipe(gulp.dest('dist/images'))
        .on('end', done);
});

//创建服务器
gulp.task('connect', function(){
    console.log('链接中。。。。');
    connect.server({
        root: host.path,
        port: host.port,
        livereload: true
    })
})

//自动打开浏览器
gulp.task('open', function(done){
    gulp.src('')
        .pipe(open({
            app: browser,
            uri: 'http://localhost:8888/view/'+host.index
        }))
        .on('end', done)
  });

//自动刷新浏览器
gulp.task('reload', function(done){
    gulp.src('')
        .pipe(connect.reload())
        .on('end', done)
});

//js打包
gulp.task('buildjs', function(done){
    gulp.src('')
        .pipe(gulpwebpack(webpackconfig, webpack))
        .pipe(gulp.dest('dist/js'))
        .on('end', done);
});

//监听任务
gulp.task('watch', function(done){
    gulp.watch('src/**/*', ['cssmin', 'fileinclude', 'reload'])
        .on('end', done)
})

//执行所有任务
gulp.task('default', ['fileinclude', 'cssmin', 'copy:images','buildjs', 'connect','watch','open']);